import * as echarts from 'echarts';
import type { EChartEventHandler } from 'my-web-core/interfaces';
import { useEffect, useRef } from 'react';

interface Props {
  option: any;
  width?: string;
  height?: string;
  eventHandlers?: EChartEventHandler[];
}

export default function EChart({
  option,
  width = '1000px',
  height = '600px',
  eventHandlers,
}: Props) {
  const chartDom = useRef(null);

  useEffect(() => {
    // Initialize the echarts instance based on the prepared dom
    const myChart = echarts.init(chartDom.current!);
    window.addEventListener('resize', myChart.resize as any);

    // Display the chart using the configuration items and data just specified.
    myChart.setOption(option);

    // Sets all event handlers on chart.
    if (eventHandlers) {
      for (const p of eventHandlers) {
        myChart.on(p.eventName!, p.query!, p.handler!);
      }
    }

    // Does cleanup.
    return () => {
      window.removeEventListener('resize', myChart.resize as any);
      myChart?.dispose();
    };
  }, [option, width, height, eventHandlers]);

  return (
    <div
      ref={chartDom}
      style={{
        width: width,
        height: height,
      }}
    ></div>
  );
}
